package com.leyou.cart.service;

import com.leyou.cart.pojo.Cart;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.UserHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

import static com.leyou.common.constants.RedisConstants.CART_USER_KEY_PREFIX;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void saveCart(Cart cart) {
        // 1.获取用户id
        UserInfo user = UserHolder.getUser();
        String userId = CART_USER_KEY_PREFIX + user.getId();
        // 2.获取cart中的商品id
        String skuId = cart.getSkuId().toString();
        // 3.获取redis的hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(userId);
        // 4.判断商品在购物车中是否已经存在
        Boolean hasKey = hashOps.hasKey(skuId);
        if (BooleanUtils.isTrue(hasKey)) {
            // 5.存在，修改
            Integer num = cart.getNum();
            // 5.1.取出来原来购物车
            String json = hashOps.get(skuId);
            cart = JsonUtils.toBean(json, Cart.class);
            // 5.2.修改数量
            cart.setNum(num + cart.getNum());
        }
        // 5.3.写入redis
        hashOps.put(skuId, JsonUtils.toJson(cart));
    }

    public List<Cart> queryCartList() {
        // 1.获取用户id
        UserInfo user = UserHolder.getUser();
        String userId = CART_USER_KEY_PREFIX + user.getId();
        // 2.获取redis的hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(userId);
        // 3.获取用户的所有购物车数据
        List<String> values = hashOps.values();
        // 4.健壮性判断
        if(CollectionUtils.isEmpty(values)){
            throw new LyException(404, "购物车为空！");
        }
        // 5.反序列化并返回
        return values.stream().map(s -> JsonUtils.toBean(s, Cart.class)).collect(Collectors.toList());
    }
}
